<template>
    <main>
        <h1>绑定新的银行卡</h1>
        <form id="payment-form" @submit.prevent="handleBind">
            <div id="card-element"></div>
            <button id="submit-button">去绑定</button>
        </form>
        
        
        <h1>已经绑定的银行卡</h1>
        <ul v-for="(item, index) in objectArray" :key="index">
            <li>序号：{{ index + 1 }}</li>
            <li>方式ID：{{ item.paymentMethodId }}</li>
            <li>卡类型：{{ item.cardBrand }}</li>
            <li>后四位：{{ item.last4Digits }}</li>
        </ul>

        <sr-messages :messages="messages" />
    </main>
</template>
<script setup>
  import { ref, onMounted } from "vue";
  import { loadStripe } from "@stripe/stripe-js";
  
  import SrMessages from "./SrMessages.vue";
  
  const messages = ref([]);
  let stripe;
  let elements;
  let cardElement;
  
  let objectArray = ref([]);
onMounted(async () => {
  const { publishableKey } = await fetch("/api/stripe/config").then((res) => res.json());
  stripe = await loadStripe(publishableKey);
  elements = stripe.elements();
  cardElement = elements.create('card');
  cardElement.mount('#card-element');

  objectArray.value  = await fetch(
      '/api/stripe/bindCardList',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            customerId: sessionStorage.getItem('stripeCustomerId'),
        }),
      }
    ).then((r) => {
      console.log('第一个then', r)
      return r.json()
    }).then((r) => {
      console.log('第二个then', r)
      return r
    });
    return objectArray;
});

const handleBind = async () => {
    stripe.createPaymentMethod({
        type: 'card',
        card: cardElement,
        billing_details: {
            name: sessionStorage.getItem('name'),
        },
    })
    .then(function(result) {
        console.log(result)
        // Handle result.error or result.paymentMethod
        if (result.error) {
            // 处理错误
            console.error(result.error.message);
        } else {
            // PaymentMethod 创建成功，将其传递给服务器进行进一步处理
            //paymentMethodId = result.paymentMethod.id;
            // 将 paymentMethodId 发送到服务器端
            // 这里你可以使用 AJAX 或其他方法将 paymentMethodId 发送到服务器
            fetch(
                '/api/user/addPaymentMethod',
                {
                    method: 'POST',
                    headers: {
                    'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        userId: sessionStorage.getItem('id'),
                        paymentMethodId: result.paymentMethod.id,
                    }),
                }).then((r) => {
                    console.log('第一个then', r)
                    return r.json()
                }).then((r) => {
                console.log('第二个then', r)
                    if (r.code == 200) {
                        //刷新已绑定银行卡列表
                    } else {
                        messages.value.push('服务错误，本地添加银行卡错误');
                    }
                });
        }
    });
}
  
</script>